<template>
  <div
    class="xsd-move"
    @mousedown="down"
    @mouseup="end"
    :style="{top:position.y+'px', left:position.x+'px'}"
  >
    <slot>
    </slot>
  </div>
</template>

<script type="text/javascript">
export default {
  props: ['positionX', 'positionY'],
  data() {
    return {
      flags: false,
      position: {
        x: 0,
        y: 0
      },
      target: null,
      screenWidth: 0,
      screenHeight: 0,
      dx: 0,
      dy: 0
    }
  },

  methods: {
    // 实现移动端拖拽
    down(event) {
      this.flags = true;
      var touch;
      if (event.touches) {
        touch = event.touches[0];
      } else {
        touch = event;
      }
      this.dx = touch.clientX - event.currentTarget.offsetLeft
      this.dy = touch.clientY - event.currentTarget.offsetTop;
      this.target = event.currentTarget;
    },
    move(event) {
      if (this.flags) {
        var touch;
        if (event.touches) {
          touch = event.touches[0];
        } else {
          touch = event;
        }
        // 定位滑块的位置
        this.position.x = touch.clientX - this.dx;
        this.position.y = touch.clientY - this.dy;
        // 限制滑块超出页面
        if (this.position.x < 0) {
          this.position.x = 0
        } else if (this.position.x > this.screenWidth - this.target.clientWidth) {
          this.position.x = this.screenWidth - this.target.clientWidth
        }
        if (this.position.y < 0) {
          console.log("2")
          this.position.y = 0
        } else if (this.position.y > this.screenHeight - this.target.clientHeight) {
          this.position.y = this.screenHeight - this.target.clientHeight
        }
        //阻止页面的滑动默认事件
        // document.addEventListener("touchmove", function () {
        //   event.preventDefault();
        // }, false);
      }
    },
    //鼠标释放时候的函数
    end() {
      this.flags = false;
    },



  },

  created() {
    if (this.positionX) {
      this.position.x = this.positionX;

    }
    if (this.positionY) {
      this.position.y = this.positionY;
    }

  },

  mounted() {
    this.screenWidth = document.documentElement.clientWidth
    this.screenHeight = document.documentElement.clientHeight
    document.addEventListener('mousemove', this.move)
  }

}

</script>

<style  scoped>
.xsd-move {
  z-index: 999;
  position: fixed;
  user-select: none;
  cursor: move;
}
</style>
